package org.codeart.apipassenger.controller;

import org.codeart.apipassenger.service.OrderService;
import org.codeart.common.constant.IdentityEnum;
import org.codeart.common.dto.OrderInfo;
import org.codeart.common.dto.TokenResult;
import org.codeart.common.request.OrderRequest;
import org.codeart.common.util.JwtUtils;
import org.codeart.common.util.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;

@RestController
@RequestMapping("/order")
public class OrderController {

    @Autowired
    private OrderService orderService;

    @PostMapping("/add")
    public R<Void> add(@RequestBody OrderRequest orderRequest, @RequestHeader("deviceCode") String deviceCode) {
        boolean b = orderService.add(orderRequest, deviceCode);
        if (b) {
            return R.ok();
        }
        return R.fail("订单创建失败");
    }

    @PostMapping("/cancel")
    public R<Void> cancel(@RequestParam("orderId") Long orderId) {
        boolean b = orderService.cancel(orderId);
        if (b) {
            return R.ok();
        }
        return R.fail("订单取消失败");
    }

    @GetMapping("/detail")
    public R<OrderInfo> detail(Long orderId) {
        return orderService.detail(orderId);
    }

    @GetMapping("/current")
    public R<OrderInfo> currentOrder(HttpServletRequest httpServletRequest) {
        String authorization = httpServletRequest.getHeader("Authorization");
        TokenResult tokenResult = JwtUtils.parseToken(authorization);
        String identity = tokenResult.getIdentity();
        if (!identity.equals(IdentityEnum.PASSENGER.value())) {
            return R.fail("仅限乘客操作!");
        }
        String phone = tokenResult.getPhone();
        return orderService.currentOrder(phone, IdentityEnum.PASSENGER.value());
    }

}
